package com.shouhuobao.take.input;

import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import com.app.Animator;
import com.iseastar.guojiang.app.AppCaptureActivity;
import com.iseastar.guojiang.app.Intents;
import com.iseastar.guojiang.consts.MsgID;
import com.iseastar.guojiang.logic.AppHttp;
import com.iseastar.guojiang.logic.JSON;
import com.iseastar.guojiang.model.ReqResult;
import com.iseastar.guojiang.tools.TextWatcherExt;
import com.shouhuobao.station.R;
import com.shouhuobao.take.BaseActivityWithScroll;
import com.shouhuobao.take.model.ContactPeopleBean;
import com.shouhuobao.take.model.PostCompanyBean;
import com.shouhuobao.take.parcel.ParcelExpressCompanyActivity;
import com.shouhuobao.take.parcel.ParcelInputPhoneAdapter;
import com.shouhuobao.take.parcel.ParcelSelectReceiverActivity;

import java.util.ArrayList;
import java.util.HashMap;

import droid.frame.utils.lang.Str;
import droid.frame.view.InputFilterExt;

/**
 * 包裹录入 test
 *
 * @author coffee<br>
 *         2017年5月22日下午3:24:52
 */
public class ParcelInputActivity extends BaseActivityWithScroll implements OnClickListener {

    private TextView mExpressCompanyName;
    private TextView mExpressNumber;//运单号
    public AutoCompleteTextView mReceiverPhone;//收件人电话
    private EditText mReceiverName;
    private TextView mRemark;
    private CheckBox mParcelBig, mParcelSmall;
    private FrameLayout mDrawerLayout;//抽屉布局
    private ImageView mDownIV;// 下拉抽屉按钮

    public ParcelInputPhoneAdapter mAdapter = null;
    public ArrayList<ContactPeopleBean> allList = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setScrollHeight(100);
        AppHttp.getInstance().getReceiverInfo();
    }

    @Override
    protected void findViewById() {
        setContentView(R.layout.take_parcel_input);
        super.findViewById();
        getAppTitle().setCommonTitle("包裹录入");
        mExpressNumber = (TextView) findViewById(R.id.parcel_express_number);
        mExpressCompanyName = (TextView) findViewById(R.id.parcel_express_companyName);
        mReceiverPhone = (AutoCompleteTextView) findViewById(R.id.parcel_receiver_phone);
        mReceiverName = (EditText) findViewById(R.id.parcel_receiver_name);
        mRemark = (TextView) findViewById(R.id.parcel_remark);
        mParcelBig = (CheckBox) findViewById(R.id.parcel_big_cb);
        mParcelSmall = (CheckBox) findViewById(R.id.parcel_small_cb);
        mParcelBig.setChecked(false);
        mParcelSmall.setChecked(true);

        mDrawerLayout = (FrameLayout) findViewById(R.id.drawer_button_layout);
        mDownIV = (ImageView) findViewById(R.id.receiver_down);
        mDrawerLayout.setOnClickListener(this);

        mReceiverPhone.setFilters(new InputFilter[]{new InputFilterExt(1)});
        findViewById(R.id.parcel_scan).setOnClickListener(this);
        final TextView parcelExpressCompany = (TextView) findViewById(R.id.parcel_express_companyName);
        parcelExpressCompany.addTextChangedListener(new TextWatcherExt() {
            @Override
            public void afterTextChanged(Editable s) {
                if (isNotEmpty(s.toString()) && isNotEmpty(mReceiverPhone.getText().toString())) {
                    setButtonEnableStyle((Button) findViewById(R.id.submit), true);
                } else {
                    setButtonEnableStyle((Button) findViewById(R.id.submit), false);
                }
            }
        });
        mReceiverPhone.addTextChangedListener(new TextWatcherExt() {
            @Override
            public void afterTextChanged(Editable s) {
                if (isNotEmpty(s.toString()) && Str.isPhoneLegal(s.toString()) && isNotEmpty(parcelExpressCompany.getText().toString())) {
                    setButtonEnableStyle((Button) findViewById(R.id.submit), true);
                } else {
                    setButtonEnableStyle((Button) findViewById(R.id.submit), false);
                }
            }
        });
        parcelExpressCompany.setOnClickListener(this);
        findViewById(R.id.parcel_small).setOnClickListener(this);
        findViewById(R.id.parcel_big).setOnClickListener(this);
        mParcelBig.setOnClickListener(this);
        mParcelSmall.setOnClickListener(this);
        setButtonEnableStyle((Button) findViewById(R.id.submit), false);
        findViewById(R.id.submit).setOnClickListener(this);
        findViewById(R.id.receiver_phone_IV).setOnClickListener(this);
        setAdapterData(allList);
        mReceiverPhone.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                try {
                    ContactPeopleBean bean = (ContactPeopleBean) mReceiverPhone.getAdapter().getItem(position);
                    if (bean != null) {
                        mReceiverPhone.setText(bean.getPhone());
                        mReceiverPhone.setSelection(bean.getPhone().length());
                        if (isNotEmpty(bean.getName())) {
                            mReceiverName.setText(bean.getName());
                            mReceiverName.setSelection(bean.getName().length());
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    public void setAdapterData(ArrayList<ContactPeopleBean> list) {
        mAdapter = new ParcelInputPhoneAdapter(list, getContext());
        mReceiverPhone.setAdapter(mAdapter);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.parcel_big:
                mParcelBig.setChecked(true);
                mParcelSmall.setChecked(false);
                break;
            case R.id.parcel_small:
                mParcelBig.setChecked(false);
                mParcelSmall.setChecked(true);
                break;
            case R.id.parcel_big_cb:
                mParcelBig.setChecked(true);
                mParcelSmall.setChecked(false);
                break;
            case R.id.parcel_small_cb:
                mParcelBig.setChecked(false);
                mParcelSmall.setChecked(true);
                break;
            case R.id.parcel_scan:
                Intent intent = new Intent();
                intent.setClass(getContext(), AppCaptureActivity.class);
                intent.setAction(Intents.station_scan_for_input);
                startActivityForResult(intent, 101);
                break;
            case R.id.parcel_express_companyName:
                intent = new Intent();
                intent.setClass(getContext(), ParcelExpressCompanyActivity.class);
                startActivityForResult(intent, 102);
                break;
            //跳转到选择联系人页面
            case R.id.receiver_phone_IV:
                intent = new Intent();
                intent.setClass(getContext(), ParcelSelectReceiverActivity.class);
                intent.putExtra("items", allList);
                startActivityForResult(intent, 104);
                break;
            //下拉抽屉
            case R.id.drawer_button_layout:
                ViewGroup drawerLayout = (ViewGroup) findViewById(R.id.drawer_content_layout);
                int height = (findViewById(R.id.express_company_ll).getHeight() * 3);
                // 如果是寄件人
                if (drawerLayout.getVisibility() == View.VISIBLE) {
                    mDownIV.setImageDrawable(getResources().getDrawable(R.drawable.drawer_down));
                    Animator.scaleY(drawerLayout, null, height, 0);
                } else {
                    drawerLayout.setVisibility(View.VISIBLE);
                    mDownIV.setImageDrawable(getResources().getDrawable(R.drawable.drawer_up));
                    //                    Animator.scaleY(drawerLayout, new Callback() {
                    //                        @Override
                    //                        public void execute(Object... result) {
                    //                            ScrollView scrollView = (ScrollView) findViewById(R.id.scrollview);
                    //                            scrollView.scrollTo(0, scrollView.getBottom());
                    //                        }
                    //                    }, 0, height);
                    Animator.scaleY(drawerLayout, null, 0, height);
                }
                break;
            case R.id.submit:
                onSubmit();
                break;
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    public boolean handleMessage(Message msg) {
        switch (msg.what) {
            case MsgID.take_parcel_input:
                cancelLoadingDialog();
                ReqResult<Object> result = JSON.parserMap(msg.obj, Object.class);
                if (checkLoginStatus(result) || result.getStatus() == 3001) {
                    showToast(result.getMessage());
                    HashMap<String, Object> resultMap = result.getResultMap();
                    String storageCode = (String) resultMap.get("storageCode");
                    Integer shelves = (Integer) resultMap.get("shelves");
                    String expressCompanyName = (String) resultMap.get("expressCompanyName");
                    Intent intent = new Intent();
                    intent.setClass(getContext(), ParcelInputResultActivity.class);
                    intent.putExtra("storageCode", storageCode);
                    intent.putExtra("shelves", shelves);
                    intent.putExtra("expressCompanyName", expressCompanyName);
                    startActivityForResult(intent, 103);
                } else {
                    showToast(result.getMessage());
                }
                return false;
            //获取联系人
            case MsgID.parcel_receive_info:
                final ReqResult<ContactPeopleBean> result1 = JSON.parseList(msg.obj, ContactPeopleBean.class);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (checkLoginStatus(result1)) {
                            allList.clear();
                            allList.addAll(result1.getResultList());
                            mAdapter.notifyDataSetChanged();
                        }
                    }
                });
                return true;
            default:
                return super.handleMessage(msg);
        }
    }

    /**
     * 提交数据到服务器
     */
    private void onSubmit() {
        if (TextUtils.isEmpty(mExpressCompanyName.getText())) {
            showToast("请选择快递公司");
            return;
        }
        if (TextUtils.isEmpty(mReceiverPhone.getText())) {
            showToast("请填入收件人电话");
            return;
        }
        //
        showLoadingDialog(null);
        AppHttp.getInstance().takeParcelInput(mExpressNumber.getText().toString(), //
                mExpressCompanyName.getText().toString(), //
                mReceiverPhone.getText().toString(), mReceiverName.getText().toString(), //
                mRemark.getText().toString(), mParcelBig.isChecked());
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        //扫描条形码或二维码返回的结果
        if (resultCode == RESULT_OK && requestCode == 101) {
            String result = data.getStringExtra("result");
            int index = result.lastIndexOf("=");
            String code2;
            if (index > -1) {
                code2 = result.substring(index + 1, result.length());
            } else {
                code2 = result;
            }
            mExpressNumber.setText(code2);
        } else if (resultCode == RESULT_OK && requestCode == 102) {
            PostCompanyBean item = (PostCompanyBean) data.getSerializableExtra("item");
            mExpressCompanyName.setText(item.getName());
        } else if (resultCode == RESULT_OK && requestCode == 103) {
            boolean finish = false;
            if (data != null) {
                finish = data.getBooleanExtra("finish", false);
            }
            if (finish == false) {
                AppHttp.getInstance().getReceiverInfo();
                mExpressNumber.setText("");
                mReceiverPhone.setText("");
                mReceiverName.setText("");
                mRemark.setText("");
            } else {
                setResult(RESULT_OK);// 告知首页、需要刷新数量
                finish();
            }
        } else if (resultCode == RESULT_OK && requestCode == 104) {
            ContactPeopleBean bean = (ContactPeopleBean) data.getSerializableExtra("item");
            if (bean != null) {
                mReceiverPhone.setText(bean.getPhone());
                mReceiverPhone.setSelection(bean.getPhone().length());
                if (!"#".equals(bean.getName())) {
                    mReceiverName.setText(bean.getName());
                    mReceiverName.setSelection(bean.getName().length());
                }
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }
}
